package com.web.manager.cyclecomm.comm;

import com.google.gson.Gson;
import com.web.config.CycleCommConfig;
import io.swagger.client.ApiException;
import io.swagger.client.api.AuthenticationApi;
import io.swagger.client.model.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * Created by easemob on 2017/3/14.
 */
@Component
public class TokenUtil {
    @Autowired
    private  CycleCommConfig cycleCommConfig;
    public static String GRANT_TYPE;
    private static String CLIENT_ID;
    private static String CLIENT_SECRET;
    private static Token BODY;
    private static AuthenticationApi API = new AuthenticationApi();
    private static String ACCESS_TOKEN;
    private static Double EXPIREDAT = -1D;
    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);

    private static TokenUtil tokenUtil;
    @PostConstruct
    public void init() {
        tokenUtil = this;
        tokenUtil.cycleCommConfig = this.cycleCommConfig;
        GRANT_TYPE =tokenUtil.cycleCommConfig.getGrant_type();
        CLIENT_ID = tokenUtil.cycleCommConfig.getClient_id();
        CLIENT_SECRET = tokenUtil.cycleCommConfig.getClient_secret();
        BODY = new Token().clientId(CLIENT_ID).grantType(GRANT_TYPE).clientSecret(CLIENT_SECRET);
    }

    /**
     * get token from server
     */


    public static void initTokenByProp() {
        String resp = null;
        try {
            resp = API.orgNameAppNameTokenPost(OrgInfo.ORG_NAME, OrgInfo.APP_NAME, BODY);
        } catch (ApiException e) {
            logger.error(e.getMessage());
        }
        logger.info("token结果获取："+resp);
        Gson gson = new Gson();
        Map map = gson.fromJson(resp, Map.class);
        ACCESS_TOKEN = " Bearer " + map.get("access_token");
        EXPIREDAT = System.currentTimeMillis() + (Double) map.get("expires_in");
    }

    /**
     * get Token from memory
     *
     * @return
     */
    public static String getAccessToken() {
        if (ACCESS_TOKEN == null || isExpired()) {
            initTokenByProp();
        }
        return ACCESS_TOKEN;
    }

    private static Boolean isExpired() {
        return System.currentTimeMillis() > EXPIREDAT;
    }

}

